from mnemoply.model.model_object import ModelObject
from mnemoply.model.hub import __connection__

from mnemoply._renewed_model.columns import  UnicodeCol, BoolCol,\
                        ForeignKey, DateCol, TimeCol, IntCol,\
                        BLOBCol, DecimalCol

from mnemoply._renewed_constants import today
from mnemoply._renewed_utils import multiple_remove, multiple_replace
from mnemoply.model import Group, CustomerTariff
from mnemoply._renewed_model import references
import turbogears
from mnemoply._renewed_common_classes import Wrapper
from mnemoply.utils import objs2ids, format_date
import datetime

class Account(ModelObject):
    
    model_title = _("Account")
    class sqlmeta:
        table = "prod_v2.account"
    
    phone_main = UnicodeCol( notNull = True,  title=_("Main phone"))
    phones_more = UnicodeCol(notNull = False, length=30, default='', title=_("More phones"))
    number =  IntCol(notNull=True,  title=_("Number"), alternateID=True)
    source =  ForeignKey("InformationSource", default=1, title=_("Information source"))

    title = property(lambda self: self.phone_main)
    
    def getSearchPhones(self):
        rep = {'+7':'8'}
        return multiple_replace(multiple_remove("%s; %s" %(self.phone_main, self.phones_more), ' ', ')', '(', '-' ), **rep)
    searchphones = property(lambda self:self.getSearchPhones())
    allphones = property(lambda self: "%s; %s"%(self.phone_main, self.phones_more))

class AccountFree(ModelObject):
    model_title = _("Account Free")
    class sqlmeta:
        table = "prod_v2.account_free"
    office = ForeignKey('Office', notNull=True, title=_("Office"))
    title = property(lambda self: self.id.__str__().rjust(7,'0'))
    is_free = property(lambda self: Account.selectBy(number=self.id).count()==0)


class Personality(ModelObject):
    model_title = _("Personality")
    class sqlmeta:
        table = "prod_v2.personality"
        
    account =      ForeignKey("Account", notNull=True, title=_("Phones"))
    surname =    UnicodeCol(length=80, notNull=True,  title=_("Surname"))
    forename =   UnicodeCol(length=80, notNull=True, title=_("Forename"))
    patronymic = UnicodeCol(length=80, notNull=True, title=_("Patronymic"))
    email =      UnicodeCol(length=140, default='', notNull=False, title=_("E-mail"))
    dateEnter = DateCol(notNull=False, title=_("Entering date"), default=today)
    isCustomer = BoolCol(notNull=False, default=False, title = _("Customer"))
    isEmployee = BoolCol(notNull=False, default=False, title = _("Personal"))

    title_short = property(lambda self: "%s %s. %s." % (self.surname, self.forename[0:1], self.patronymic[0:1]))
    title = property(lambda self: "%s %s %s" % (self.surname, self.forename, self.patronymic))
    title_full = property(lambda self: "%s %s" %(self.title, self.account.searchphones))

class StudentNew(Personality):
    class sqlmeta:
        table = "prod_v2.personality"
    model_title = _("Student")
    isStudent = BoolCol(notNull=False, default=True, title = _("Student"))
    birthday =   DateCol(default=datetime.date(2000,1,1), notNull=True, title=_("Birthday"))
    student_type = ForeignKey("StudentType", notNull = True, title = _("Student type"))
    
    surname_translit =    UnicodeCol(length=80,  default=None, title=_("Surname translit"))
    forename_translit =   UnicodeCol(length=80,  default=None, title=_("Forename translit"))
    patronymic_translit = UnicodeCol(length=80,  default=None, title=_("Patronymic translit"))
    
    school_name = UnicodeCol(length=80,  notNull=True, title=_("School name"))
    school_form = IntCol(notNull=True,title=_("Form enter"))
    academic_year_admission = IntCol(notNull=True,title=_("Year enter"), default=today.year)


class GroupReserve(ModelObject):
    model_title = _("Group reserve")
    class sqlmeta:
        table = "prod_v2.education_agreement"
    account = ForeignKey("Account",  notNull = True, title = _("Account"))
    dateEnter = DateCol(notNull=False, title=_("Entering date"), default=today)
    student = ForeignKey("Personality", notNull = True, title = _("Student"))
    customer = ForeignKey("Personality", notNull = True, title = _("Customer"))
    discont = ForeignKey("Discont", notNull = False, default=None, title = _("First discont"))
    group = ForeignKey("Group", notNull = True, title = _("Group"))
    cameFrom = ForeignKey("CameFrom", notNull = False, default=1, title = _("Came from"))
    comment = UnicodeCol(length=80, notNull=False, default='', title=_("Comment"))
   # prefered_day = UnicodeCol(length=80,  default="::::::", title=_("Prefered day"))
    title = property(lambda self:"%s\n%s\n(%s)"
                     %(self.group.title,self.student.title,self.customer.title_short,))
    
   
    @classmethod
    def handle_update(cls, obj, kw):
        pass

class EducationAgreement(GroupReserve):
    model_title = _("Education agreement")
    class sqlmeta:
        table = "prod_v2.education_agreement"
    dateCreation = DateCol(notNull=False, title=_("Payment date"), default=None)
    dateBegin = DateCol(notNull=False, title=_("Date begin"), default=None)
    dateEnd = DateCol(notNull=False, title=_("Date end"), default=None)
    dateCancellation = DateCol(notNull=False, title=_("Date cancellation"), default=None)
    amount_to = IntCol(notNull=False, default=0, title=_("Amount to"))
    amount_reserve = IntCol(notNull=False, default=0, title=_("Reserve"))
    amount_from = IntCol(notNull=False, default=0, title=_("Amount from"))
    amount_to_account = IntCol(notNull=False, default=0, title=_("Amount to account"))
    printCount = IntCol(notNull=True, default=0, title=_("Print count"))
    def report_obj(self):
        res = Wrapper()
        agr =self
        st =  StudentNew .get(agr.student.id)
        res.customer = agr.customer.title
        res.student = agr.student.title
        res.birthday = st.birthday
        res.school_name = st.school_name
        res.school_form = st.school_form
        res.phone = agr.customer.account.phone_main
        res.agr_id  = agr.id
        res.group =  agr.group.shortName
        res.end_date = format_date(agr.group.endDate)
        res.start_date =format_date(agr.group.startDate)
        res.duration = agr.group.lessonPeriod
        res.plan = agr.group.initialPlan.name
        res.tariff = agr.group.customerTariff.title
        res.comment =agr.group.initialPlan.comment
        res.trend = agr.group.initialPlan.trend.name
        return res


class Price(CustomerTariff):
    model_title = _("Customer tariff")
    class sqlmeta:
        table = "prod.customer_tariff"
    price_for = ForeignKey("PriceFor", notNull = False, default = 2, title = _("Price For"))
    amount = IntCol(notNull=False, default=0, title=_("Amount"))
    prepayment = IntCol(notNull=False, default=0, title=_("Prepayment"))
    typicalLessons = IntCol(notNull=False, title=_("Typical lessons"))
    comment = UnicodeCol(length=80, notNull=False, default='', title=_("Comment"))
    title = property(lambda self: '%s %s %s'%(self.amount,_('rub.') ,
                                              self.price_for.title if self.price_for else 'test' ))

class AccountCashOperation(ModelObject):
    model_title = _("Account cash operation")
    class sqlmeta:
        table = "prod_v2.account_cash_operation"
    account = ForeignKey("Account", notNull = True, title = _("Account"))
    date = DateCol(notNull=False, title=_("Date"), default=today)
    amount = IntCol(notNull=True, title=_("Amount"))
    register = ForeignKey("CashRegister",   notNull = True, title = _("Register"))
    comment = UnicodeCol(length=80, notNull = False,  default='', title=_("Comment"))
    coupon = ForeignKey("Coupon",  notNull = True, title = _("Coupon"))
    direction = IntCol(notNull=False, default=1, title=_("Direction"))
    title = property(lambda self:"%s %s: %s.00 %s"%(self.register.organization.title, self.date, self.amount,_("rub.")))
    